require 'rexml/document'

###############################
#
# These functions handle the trigger, it takes the XML
# Identifies messages that it needs to respond to, and
# reacts accordingly.
#
###############################

class Squick

  def doSubstitutions(str, msg, regGroups)
    str.gsub!("@@@NICK@@@", @nick)
    str.gsub!("@@@CHAN@@@", "#{@channel}")
    str.gsub!("@@@USER@@@", msg.user)

    str.match(/@@@([0-9]*)@@@/)
    if $~ != nil then
      $~.length.times do |i|
        str.gsub!("@@@#{i}@@@", regGroups[i])
      end
    end
    return str
  end

  def checkAgainstMessageTriggers(msg)
    @triggers.each do |triggerFile|
      triggerFile.each_element("Triggers/Trigger") do |trigger|
        function = trigger.get_elements("Function").shift.text
        response = send function, msg

        # Saying the response
        sayToChan(response) if(response != nil && response.length > 0)
      end
    end
  end


  #see if there is a trigger for when this user joins
  def checkAgainstJoiningTriggers(nick)
    @triggers.each do |triggerFile|
      triggerFile.each_element("Triggers/JoinTrigger") do |trigger|
        function = trigger.get_elements("Function").shift.text
        response = send function, nick

        # Saying the response
        sayToChan(response) if(response != nil && response.length > 0)
      end
    end
  end

  #see if there is a trigger for when this user parts
  def checkAgainstPartingTriggers(nick)
    @triggers.each do |triggerFile|
      triggerFile.each_element("Triggers/PartTrigger") do |trigger|
        function = trigger.get_elements("Function").shift.text
        response = send function, nick

        # Saying the response
        sayToChan(response) if(response != nil && response.length > 0)
      end
    end
  end


  #see if there is a trigger for NAMES lists
  def checkAgainstNamesTriggers(names)
    @triggers.each do |triggerFile|
      triggerFile.each_element("Triggers/NamesTrigger") do |trigger|
        function = trigger.get_elements("Function").shift.text
        response = send function, names.split

        # Saying the response
        sayToChan(response) if(response != nil && response.length > 0)
      end
    end
  end

end
